package com.tianji.learning.delay;



import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayTask<D> implements Delayed {
    // 延时执行时间的毫秒值
    private Long deadLineNanos;

    // 延时任务的数据
    private  D data;

    public DelayTask(Duration duration, D data) {
        this.deadLineNanos = System.nanoTime() + duration.toNanos();
        this.data = data;
    }


    /**
     * 用来获取队列中每个任务距离当前时间还有多久被执行
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        // 返回当前任务距离当前时间的毫秒值并将其转换为指定的时间单位
        return unit.convert(deadLineNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    /**
     * 对延时队列中的任务进行排序（根据getDelay获取的任务延时时间进行排序，值越小，越先被执行）
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (diff > 0){
            return 1;
        }else if (diff < 0){
            return -1;
        }else {
            return 0;
        }
    }
}
